//
//  CZQSelctChoseView.m
//  coachmanage
//
//  Created by zhiqiang chen on 2018/4/11.
//  Copyright © 2018年 众拳科技. All rights reserved.
//

#import "CZQSelctChoseView.h"
#import "VenueModel.h"
@implementation CZQSelctChoseViewCell

-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    
    if (self) {
        
        UIButton *selectBtn = [[UIButton alloc] init];
        [selectBtn setImage:@"icon_radio"];
        [selectBtn setSelectedImage:@"icon_radioch"];
        [self.contentView addSubview:selectBtn];
        self.selectBtn = selectBtn;
        
        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.font = BigFont;
        titleLabel.textColor = CSColorFromRGB(0x0a0a0a);
        [self.contentView addSubview:titleLabel];
        self.titleLabel = titleLabel;
        
        [self setConstraints];
    }
    
    return self;
}

-(void)setConstraints{
    
    [self.selectBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(self.contentView).offset(10);
        
        make.centerY.mas_equalTo(self.contentView);
    }];
    
    [self.titleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.centerY.mas_equalTo(self.contentView);
        
        make.left.mas_equalTo(self.selectBtn.mas_right).offset(10);
    }];
}

@end

@interface CZQSelctChoseView()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>

@property(nonatomic,strong)NSArray *dataSource;

@property(nonatomic,strong)NSMutableArray *searchDataSource;

@property(nonatomic,assign)NSInteger selectRow;

@end

@implementation CZQSelctChoseView

-(NSMutableArray *)searchDataSource
{
    if (!_searchDataSource) {
        _searchDataSource = [NSMutableArray array];
    }
    return _searchDataSource;
}

-(id)initWithFrame:(CGRect)frame{
    
    CGRect initialFrame;
    
    if (CGRectIsEmpty(frame)) {
        
        initialFrame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
        
    } else {
        
        initialFrame = frame;
    }
    
    self = [super initWithFrame:initialFrame];
    
    if (self) {
        
        self.selectRow = -1;
        
        
        UIView *alphaView = [[UIView alloc] init];
        alphaView.backgroundColor = [CSBlackColor colorWithAlphaComponent:0.4];
        [self addSubview:alphaView];
        self.alphaView = alphaView;
        
        UIView *whiteView = [[UIView alloc] init];
        whiteView.backgroundColor = CSWhiteColor;
        [self addSubview:whiteView];
        self.whiteView = whiteView;
        
        
        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.text = @"绑定门派";
        titleLabel.font = BoldBigFont;
        [whiteView addSubview:titleLabel];
        self.titleLabel = titleLabel;
        
        UIButton *closeBtn = [[UIButton alloc] init];
        [closeBtn setImage:@"pop_icon_close"];
        [closeBtn addTarget:self action:@selector(hiddenWithAnimation)];
        [whiteView addSubview:closeBtn];
        self.closeBtn = closeBtn;
        
        UIView *lineView = [[UIView alloc] init];
        lineView.backgroundColor = LineBackGroundColor;
        [whiteView addSubview:lineView];
        self.lineView = lineView;
        
        /**
         添加新来源
         */
        UILabel *courseLineLabel = [[UILabel alloc] init];
        courseLineLabel.backgroundColor = ButtonBackGroundColor;
        [whiteView addSubview:courseLineLabel];
        self.courseLineLabel = courseLineLabel;
        
        /**
         添加新来源
         */
        UILabel *courseIntroduceLabel = [[UILabel alloc] init];
        courseIntroduceLabel.font =  TitleBoldFont;
        //        courseIntroduceLabel.text = @"添加新来源";
        [whiteView addSubview:courseIntroduceLabel];
        self.courseIntroduceLabel = courseIntroduceLabel;
        
        /**
         输入来源
         */
        UITextField *inputTF = [[UITextField alloc] init];
        inputTF.leftViewMode = UITextFieldViewModeAlways;
        inputTF.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 0)];
        inputTF.placeholder = @"请输入查询";
        inputTF.layer.cornerRadius = 2;
        inputTF.layer.borderWidth = 0.5;
        inputTF.delegate = self;
        inputTF.font = MidBigFont;
        inputTF.layer.borderColor = LineBackGroundColor.CGColor;
        [whiteView addSubview:inputTF];
        self.inputTF = inputTF;
        
        /**
         添加按钮
         */
        UIButton *addBtn = [[UIButton alloc] init];
        [addBtn addTarget:self action:@selector(addSource)];
        addBtn.backgroundColor = ButtonBackGroundColor;
        [addBtn setTitle:@"搜索"];
        addBtn.titleLabel.font = MidBigFont;
        [addBtn setTitleColor:CSColorFromRGB(0x0a0a0a)];
        addBtn.userInteractionEnabled = YES;
        [whiteView addSubview:addBtn];
        self.addBtn = addBtn;
        
        UIView *lineView1 = [[UIView alloc] init];
        lineView1.backgroundColor = LineBackGroundColor;
        [whiteView addSubview:lineView1];
        self.lineView1 = lineView1;
        
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.showsVerticalScrollIndicator = NO;
        tableView.separatorStyle = UITableViewCellSelectionStyleNone;
        [tableView registerClass:[CZQSelctChoseViewCell class] forCellReuseIdentifier:@"SouceAlertTableViewCell"];
        [whiteView addSubview:tableView];
        self.tableView = tableView;
        
        MOFSBottomView *bottomView = [[MOFSBottomView alloc] init];
        [whiteView addSubview:bottomView];
        self.bottomView = bottomView;
        
        __weak __typeof(self) weakSelf = self;
        
        self.bottomView.cancelBlock = ^ {
            
            [weakSelf hiddenWithAnimation];
            
            
            if (weakSelf.cancelBlock) {
                
                weakSelf.cancelBlock();
            }
            
        };
        
        self.bottomView.commitBlock = ^ {
            
            
            
            if (weakSelf.commitBlock) {
                
                if (weakSelf.selectRow < 0) {
                    
                    [MBProgressHUD showText:@"请选择一项" toview:self];
                    
                    return ;
                }
                
                NSDictionary *dic = weakSelf.searchDataSource[weakSelf.selectRow];
                
                
                NSString *dataStr = [[dic objectForKey:@"Childrens"] toJSONString];
                
                weakSelf.commitBlock(dataStr);
                
                
                if (weakSelf.pandID) {
                    
                    
                    //正常流程先申请加入门派，后台审核通过绑定门派
#warning 申请加入门派
                    [MBProgressHUD showMessage:@"请求中..." toView:self];
                    
                    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
                    
                    
                    
                    [params setObject:[dic objectForKey:@"PID"] forKey:@"SectID"];
                    
                    NSString *userid = [[NSUserDefaults standardUserDefaults] valueForKey:@"UserID"];
                    
                    [params setValue:userid forKey:@"UserID"];
                    
                    [HTTPTool POSTRaw:Post_MasterApply_JoinSect parameters:params
                     
                              success:^(id responseObject){
                                  
                                  [MBProgressHUD hideHUDForView:self];
                                  
                                  if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0) {
                                      
                                      [MBProgressHUD showText:@"申请成功"];
                                      
                                      [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isCompleteInfo"];
                                      
                                      
                                      
                                      [[NSUserDefaults standardUserDefaults] setValue:[dic objectForKey:@"PID"] forKey:@"SectID"];
                                      
                                      //审核中
                                      [JHSysAlertUtil presentAlertViewWithTitle:@"温馨提示" message:@"暂时无法使用，等待后台审核。" confirmTitle:@"退出" handler:^{
                                          exit(0);
                                      }];
                                      
                                      
                                      
                                      
                                      
                                      [weakSelf removeFromSuperview];
                                  }
                                  
                              }
                     
                              failure:^(NSError *error){
                                  
                                  [MBProgressHUD hideHUDForView:self];
                              }];
                    
                }else
                {
                    [weakSelf removeFromSuperview];
                }
                
                
                
                
            }
        };
        
        [self setConstraints];
        
        
        
        
    }
    
    return self;
}

-(void)setConstraints{
    
    [self.alphaView mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.mas_equalTo(self);
    }];
    
    [self.whiteView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(self);
        make.left.mas_equalTo(self).offset(20);
        make.right.mas_equalTo(self).offset(-20);
    }];
    
    [self.titleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.whiteView).offset(20);
        make.centerX.mas_equalTo(self.whiteView);
    }];
    
    [self.closeBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.whiteView).offset(-10);
        make.top.mas_equalTo(self.whiteView).offset(10);
    }];
    
    [self.lineView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.titleLabel.mas_bottom).offset(30);
        make.left.width.mas_equalTo(self.whiteView);
        make.height.mas_equalTo(1);
    }];
    
    /**
     添加新来源
     */
    [self.courseLineLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.centerY.mas_equalTo(self.courseIntroduceLabel);
        
        make.left.mas_equalTo(self.whiteView).offset(20);
        
        make.width.mas_equalTo(0);
        
        make.height.mas_equalTo(0);
    }];
    
    /**
     添加新来源
     */
    [self.courseIntroduceLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(self.lineView.mas_bottom).offset(0);
        make.height.mas_equalTo(0);
        make.left.mas_equalTo(self.courseLineLabel.mas_right).offset(10);
    }];
    
    [self.inputTF mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(self.courseIntroduceLabel.mas_bottom).offset(30);
        
        make.left.mas_equalTo(self.courseLineLabel);
        
        make.height.mas_equalTo(40);
        
        make.right.mas_equalTo(self.addBtn.mas_left).offset(2);
    }];
    
    /**
     添加按钮
     */
    [self.addBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.centerY.mas_equalTo(self.inputTF);
        
        make.right.mas_equalTo(self.whiteView).offset(-20);
        
        make.height.mas_equalTo(40);
        
        make.width.mas_equalTo(80);
    }];
    
    [self.lineView1 mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(self.inputTF.mas_bottom).offset(25);
        
        make.left.mas_equalTo(self.inputTF);
        
        make.height.mas_equalTo(1);
        
        make.right.mas_equalTo(self.addBtn);
        
    }];
    
    [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(self.lineView1.mas_bottom).offset(20);
        
        make.left.mas_equalTo(self.whiteView).offset(10);
        
        make.right.mas_equalTo(self.whiteView).offset(-10);
        
        make.height.mas_equalTo(200);
    }];
    
    [self.bottomView mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(self.tableView.mas_bottom);
        
        make.left.width.bottom.mas_equalTo(self.whiteView);
        
        make.bottom.mas_equalTo(self.whiteView);
    }];
}

-(void)loadData{
    
    
    
    
    
    [HTTPTool GET:self.urlString parameters:nil
     
          success:^(id responseObject){
              
              NSLog(@"%@",responseObject);
              
              if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0) {
                  
                  NSMutableArray *resultArray = [NSMutableArray array];
                  
                  resultArray = [responseObject objectForKey:@"rows"];
                  
                  
                  self.dataSource = resultArray;
                  
                  self.searchDataSource = [NSMutableArray arrayWithArray:self.dataSource];
                  
                  [self.tableView reloadData];
              }
              
          }
     
          failure:^(NSError *error){
              
          }];
}

#pragma mark 查找
-(void)addSource{
    
    if ([self.inputTF.text isEmptyString]) {
        
        [MBProgressHUD showText:@"请输入"];
        
        self.searchDataSource = [NSMutableArray arrayWithArray:self.dataSource];
        
        [self.tableView reloadData];
        
        return;
    }
    
    [self.searchDataSource removeAllObjects];
    for (NSDictionary *dic in self.dataSource) {
        
        if ([[dic objectForKey:@"Name"] containsString:self.inputTF.text]) {
            [self.searchDataSource addObject:dic];
        }
        
    }
    
    
    [self.tableView reloadData];
    //
    //    BrandModel *brand = [BrandModel brand];
    //
    //    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    //
    //    [params setObject:@"来源" forKey:@"Type"];
    //
    //    [params setObject:self.inputTF.text forKey:@"Name"];
    //
    //    [params setObject:brand.brandID forKey:@"BrandID"];
    //
    //    [HTTPTool POSTRaw:Post_ADD_ShopStatus parameters:params
    //
    //              success:^(id responseObject){
    //
    //                  if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0) {
    //
    //                      [self.dataSource addObject:self.inputTF.text];
    //
    //                      [self.tableView reloadData];
    //
    //                      [MBProgressHUD showText:@"添加成功"];
    //                  }
    //
    //              }
    //
    //              failure:^(NSError *error){
    //
    //              }];
}

#pragma mark UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.searchDataSource.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CZQShopBandChoseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SouceAlertTableViewCell"];
    
    NSDictionary *dic = [self.searchDataSource objectAtIndex:indexPath.row];
    
    cell.titleLabel.text = [dic objectForKey:@"Name"];
    
    if (indexPath.row == self.selectRow) {
        
        cell.selectBtn.selected = YES;
    }
    else{
        
        cell.selectBtn.selected = NO;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 60;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    self.selectRow = indexPath.row;
    
    [self.tableView reloadData];
}

- (void)showWithAnimation {
    [self addViews];
    self.alphaView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.0];
    CGFloat height = self.whiteView.frame.size.height;
    self.whiteView.center = CGPointMake(SCREEN_WIDTH / 2, SCREEN_HEIGHT + height / 2);
    [UIView animateWithDuration:0.25 animations:^{
        self.whiteView.center = CGPointMake(SCREEN_WIDTH / 2, SCREEN_HEIGHT - height / 2);
        self.alphaView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.4];
    }];
    
}

- (void)hiddenWithAnimation {
    CGFloat height = self.whiteView.frame.size.height;
    [UIView animateWithDuration:0.25 animations:^{
        self.whiteView.center = CGPointMake(SCREEN_WIDTH / 2, SCREEN_HEIGHT + height / 2);
        self.alphaView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.0];
    } completion:^(BOOL finished) {
        [self hiddenViews];
    }];
}

- (void)addViews {
    
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    
    [window addSubview:self];
}

- (void)hiddenViews {
    
    [self removeFromSuperview];
    
    [JHSysAlertUtil presentAlertViewWithTitle:@"温馨提示" message:@"退出程序." confirmTitle:@"退出" handler:^{
        exit(0);
    }];
    
    
    
    
}

-(void)textFieldDidBeginEditing:(UITextField *)textField{
    
    //    if ([self.inputTF.text isEmptyString]) {
    //
    //        self.addBtn.userInteractionEnabled = NO;
    //
    //        self.addBtn.backgroundColor = BackGroundColor;
    //    }
    //    else{
    //
    //        self.addBtn.userInteractionEnabled = YES;
    //
    //        self.addBtn.backgroundColor = ButtonBackGroundColor;
    //    }
}


-(void)setUrlString:(NSString *)urlString
{
    _urlString = urlString;
    
    if (self.pandID) {
        
        //获取数据
        NSArray *dataArr = [self.pandID JSONValue];
        
        self.dataSource = [NSMutableArray arrayWithArray:dataArr];
        
        self.searchDataSource = [NSMutableArray arrayWithArray:self.dataSource];
        
        [self.tableView reloadData];
        
    }else
    {
        [self loadData];
    }
}


-(NSMutableArray *)dataSource{
    
    if (!_dataSource) {
        
        _dataSource = [NSMutableArray array] ;
    }
    
    return _dataSource;
}
@end




